package cn.itcast.itcaststore.web.servlet.manager;


import cn.itcast.itcaststore.serive.ProductService;
import cn.itcast.itcaststore.serive.impl.ProductServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 下载销售数据
 */
@WebServlet("/admin/download")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取年份和月份
        String year = req.getParameter("year");
        String month = req.getParameter("month");
        //创建service层对象
        ProductService productService = new ProductServiceImpl();
        //调用service层用于查询销售数据的方法download()
       List<Object[]> ps = productService.download(year,month);
       //拼接文件名
        String fileName = year+"年"+month+"月销售榜单.cvs";
        //使客户端浏览器区分不同种类的数据
        resp.setContentType(this.getServletContext().getMimeType(fileName));
        //设置文件名
        resp.setHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes("GBK"),"ISO8859-1"));
        resp.setCharacterEncoding("gbk");
        //向文件中写入数据
        PrintWriter out = resp.getWriter();
        out.println("商品名称，销售数量");
        for (int i = 0; i < ps.size(); i++){
            Object[] arr = ps.get(i);
            out.println(arr[0]+","+arr[1]);
        }
        //刷新流
        out.flush();
        //关闭流
        out.close();
    }
}
